<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2019-11-27
 * Time: 11:24
 */

namespace app\api\service;

use app\api\model\Member;
use app\api\model\PickDeliverStaff;
use app\api\model\User;
use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\ParameterException;
use app\lib\exception\TokenException;
use think\Exception;
use think\facade\Request;
use think\facade\Cache;

class Token
{
    /**
     * 生成token值
     */
    public function generateToken()
    {
        //32字符组成的一组随机字符串
        $randChars = getRandChar(32);
        //三组字符串进行md5加密
        $timestamp = $_SERVER['REQUEST_TIME'];
        //salt
        $salt = config('secure.token_salt');
        return md5($randChars.$timestamp.$salt);
    }

    //根据token获取缓存中某一个字段的值
    public static function getCurrentTokenVar($key){
        $token = Request::instance()
            ->header('token');
        $vars = Cache::get($token);
        if(!$vars){
            throw new TokenException();
        }else{
            if(!is_array($vars)){
                $vars = json_decode($vars,true);
            }
            if(array_key_exists($key,$vars)){
                return $vars[$key];
            }else{
                throw new Exception('尝试获取的token变量不存在');
            }
        }
    }

    public static function getCurrentUid(){
        $uid = self::getCurrentTokenVar('uid');
        return $uid;
    }

    //用户和管理员都可以访问的接口权限
    public static function needPrimaryScope(){
        $scope = self::getCurrentTokenVar('scope');
        if($scope)
        {
            if($scope >= ScopeEnum::User)
            {
                return true;
            }
            else{
                throw new ForbiddenException();
            }
        }
        else{
            throw new TokenException();
        }
    }

    //只有用户才可以访问的接口权限
    public static function needExclusiveScope()
    {
        $scope = self::getCurrentTokenVar('scope');
        if($scope)
        {
            if($scope == ScopeEnum::User)
            {
                return true;
            }
            else{
                throw new ForbiddenException();
            }
        }
        else{
            throw new TokenException();
        }

    }

    /**
     * 验证用户token
     */
    public static function verifyToken($token)
    {
        $exist = Cache::get($token);
        if($exist)
        {
            return true;
        }
        else{
            return false;
        }
    }

    /**
     * 判断用户是否过期
     */
    public function checkMember()
    {
        $uid = self::getCurrentUid();
        $user = User::get($uid);
        if($user['status'] == 0) {
            throw new ParameterException([
                'msg' => [
                    'member' => '请先进行登录',
                ]
            ]);
        }
        $member = Member::where('user_id',$uid)->find();
        if(!$member) {
            throw new ParameterException([
                'msg' => [
                    'member' => '请先进行会员认证',
                ]
            ]);
        }
        if($user['member_end_time'] < time()) {
            throw new ParameterException([
                'msg' => [
                    'member' => '会员已过期',
                ]
            ]);
        }
    }


    protected static function makeOrderNo()
    {
        $yCode = array('A','B','C','D','E','F','G','H','I','J');
        $orderSn =
            $yCode[intval(date('Y')) - 2020] . strtoupper(dechex(date('m'))) . date('d') .
            substr(time(),-5) . substr(microtime(),2,5) . sprintf('%02d',rand(0,99));
        return $orderSn;
    }

    // 判断取送员信息
    public static function judgeStaff($user)
    {
        if($user['staff_status'] != 1) {
            throw new ParameterException([
                'msg' => [
                    'staff' => '您还不是取送员'
                ]
            ]);
        }
        $staff = PickDeliverStaff::where('user_id',$user['id'])->find();
        if(!$staff) {
            throw new ParameterException([
                'msg' => [
                    'staff' => '您还不是取送员'
                ]
            ]);
        }
        return $staff;
    }
}